package com.zretc.controller;

import com.aliyuncs.exceptions.ClientException;
import com.github.pagehelper.PageInfo;
import com.zretc.entity.User;
import com.zretc.service.UserService;
import com.zretc.util.AliSMSUtil;
import com.zretc.util.BaiDuFace;
import com.zretc.util.Util;
import org.apache.poi.ss.formula.functions.T;
import org.aspectj.apache.bcel.generic.RET;
import org.aspectj.apache.bcel.generic.RETURN;
import org.json.HTTP;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;


@Controller
@RequestMapping("/user")
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @RequestMapping("/findUserInfo")
    @ResponseBody
    public PageInfo<User> findUserInfo(String userName, Integer state, @RequestParam(value = "pageNum") Integer pageNum, @RequestParam(value = "pageSize") Integer pageSize) {
        Map<String, Object> map = new HashMap<>();
        map.put("pageNum", pageNum);
        map.put("pageSize", pageSize);
        map.put("userName", userName);
        map.put("state", state);
        // 调用service层方法，查询用户列表并分页
        PageInfo<User> userList = userService.getUserList(map);
        return userList;
    }

    @RequestMapping("/updateState")
    @ResponseBody
    public int updateState(@RequestParam(value = "state") Integer state, @RequestParam(value = "userId") String userId) {
        // 调用业务层的方法，修改用户的审核状态
        return userService.updateStateByUserId(state, userId);
    }

    @RequestMapping("/deleteUserByUserNo")
    @ResponseBody
    public int deleteUserByUserNo(@RequestParam(value = "userId") String userId) {

        logger.info("=====================================");
        // 调用业务层的方法，删除用户
        return userService.deleteUserByUserNo(userId);
    }

    @RequestMapping("/faceUpload")
    @ResponseBody
    public Boolean faceUpload(@RequestParam(value = "img") String img) {
        logger.debug("=================================" + img);
        return true;
    }

    @RequestMapping("/faceLogin")
    @ResponseBody
    public ResponseEntity faceLogin(@RequestParam(value = "img") String img) {
        String result = BaiDuFace.faceSearch(img);
        //response.sendRedirect("/index.jsp");
        //ModelAndView modelAndView = new ModelAndView("redirect:/index.jsp");
        //modelAndView.addObject("user", user);
        return new ResponseEntity(result, HttpStatus.OK);
    }

    @RequestMapping("/faceLoginSuccess")
    @ResponseBody
    public ResponseEntity faceLogin(@RequestParam(value = "userId") String userId, HttpSession session) {

        User login = userService.login(userId);
        if (login != null) {
            session.setAttribute("user", login);
            return new ResponseEntity(login, HttpStatus.OK);
        } else {
            return new ResponseEntity(null, HttpStatus.NO_CONTENT);
        }
    }

    @RequestMapping("/logOut")
    @ResponseBody
    public Boolean faceLogin(HttpSession session) {
        session.removeAttribute("user");
        if (session.getAttribute("user") == null) {
            return true;
        } else {
            return false;
        }
    }

    @RequestMapping("/selectUserView")
    @ResponseBody
    public User userView(@RequestParam(value = "userId") String userId) {
        User user = userService.findUserViewByUserId(userId);
        return user;
    }


    @RequestMapping("/getUserById")
    @ResponseBody
    public ResponseEntity<User> getUserById(@RequestParam(value = "userId") String userId, HttpSession session) {
        Map<String, Object> params = new HashMap<>();
        params.put("userId", userId);
        User userByCondition = userService.findUserByCondition(params);
        if (userByCondition != null) {
            session.setAttribute("user", userByCondition);
            return new ResponseEntity<>(userByCondition, HttpStatus.OK);
        } else {
            return new ResponseEntity<>(null, HttpStatus.NO_CONTENT);
        }
    }

    @RequestMapping("/autoLogin")
    @ResponseBody
    public Boolean autoLogin(String userPhone, String md5, HttpSession session) {
        Map<String, Object> params = new HashMap<>();
        params.put("userPhone", userPhone);
        params.put("userPsw", md5);
        User userByCondition = userService.findUserByCondition(params);
        if (userByCondition != null) {
            session.setAttribute("user", userByCondition);
            return true;
        } else {
            return false;
        }
    }


    @RequestMapping("/pswLogin")
    @ResponseBody
    public ResponseEntity<User> pswLogin(String phoneNumberForPsw, String passWord, HttpSession session) {
        Map<String, Object> params = new HashMap<>();
        params.put("userPhone", phoneNumberForPsw);
        params.put("userPsw", Util.getMd5(passWord));
        User userByCondition = userService.findUserByCondition(params);
        if (userByCondition != null) {
            session.setAttribute("user", userByCondition);
            return new ResponseEntity<>(userByCondition, HttpStatus.OK);
        } else {
            return new ResponseEntity<>(null, HttpStatus.NO_CONTENT);
        }
    }

    @RequestMapping("/validateCodeLogin")
    @ResponseBody
    public ResponseEntity<User> validateCodeLogin(@RequestParam(value = "phoneNumberLogin") String phoneNumberLogin, @RequestParam(value = "validateCode") String validateCode, HttpSession session) {
        if (session.getAttribute("fastLoginCode") == null) {
            return new ResponseEntity<>(null, HttpStatus.NO_CONTENT);
        } else {
            Map<String, Object> param = new HashMap<>();
            param.put("userPhone", phoneNumberLogin);
            User userByCondition = userService.findUserByCondition(param);
            String session1 = session.getAttribute("fastLoginCode").toString();
            if (session1.equals(validateCode) && userByCondition != null) {
                session.removeAttribute("fastLoginCode");
                session.setAttribute("user", userByCondition);
                return new ResponseEntity<>(userByCondition, HttpStatus.OK);
            } else if (userByCondition == null && session1.equals(validateCode)) {
                User user = new User(Util.getUUID(), "用户" + phoneNumberLogin, Util.getMd5(phoneNumberLogin.substring(0, 8)), phoneNumberLogin, null, null);
                session.setAttribute("user", user);
                userService.insertUser(user);
                session.removeAttribute("fastLoginCode");
                return new ResponseEntity<>(user, HttpStatus.OK);
            } else {
                return new ResponseEntity<>(null, HttpStatus.NO_CONTENT);
            }
        }
    }


    @RequestMapping("/getValidateCode")
    @ResponseBody
    public Boolean getValidateCode(@RequestParam(value = "phoneNumber") String phoneNumber, HttpSession session) {
        String s = "";
        try {
            s = AliSMSUtil.sendCode(phoneNumber);
        } catch (ClientException e) {
            e.printStackTrace();
            return false;
        }
        logger.debug("=====================" + s + "=======================");
        session.setAttribute("fastLoginCode", s);
        final Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                session.removeAttribute("fastLoginCode");
                timer.cancel();
            }
        }, 5 * 60 * 1000);
        return true;
    }

    @RequestMapping(value = "/updateUserView", method = RequestMethod.POST)
    @ResponseBody
    public Boolean updateView(String userName, String telephone, String password, MultipartFile userFace, Double x, Double y, Double destWidth, Double destHeight, Double finalWidth, Double finalHeight, HttpSession session) throws IOException {
        String fileSuffix = "";
        String date = "";
        if (userFace.getSize() != 0) {
            // 获取文件名
            String filename = userFace.getOriginalFilename();
            logger.debug("=============" + filename);
            // 自定义文件名 + 文件后缀名
            fileSuffix = filename.substring(filename.lastIndexOf("."));
            logger.debug("=============" + fileSuffix);
            date = System.currentTimeMillis() + "";
            // 文件存储在指定的服务器中
            File file = new File("D:/EDS/images/user/" + date + fileSuffix);
            userFace.transferTo(file);
            Util.abscut("D:/EDS/images/user/" + date + fileSuffix, x.intValue(), y.intValue(), destWidth.intValue(), destHeight.intValue(), finalWidth.intValue(), finalHeight.intValue());
        }
        // 从session中获取用户编号
        User user = (User) session.getAttribute("user");
        Map<String, Object> map = new HashMap<>();
        map.put("userId", user.getUserId());
        map.put("userName", userName);
        map.put("userPhone", telephone);
        map.put("userPsw", password);
        if (!"".equals(date + fileSuffix)) {
            map.put("userFace", date + fileSuffix);
        }
        if (userService.updateUserViewByUserId(map)) {
            User newUser = userService.findUserViewByUserId(user.getUserId());
            session.setAttribute("user", newUser);
            return true;
        } else {
            return false;
        }
    }

}
